import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/news_category.dart';
import 'package:kxy_flutter_app/r.dart';
import 'package:kxy_flutter_app/view/news/news_list_widget.dart';
import 'package:kxy_flutter_app/view/root/view_model/app_info_model.dart';
import 'package:provider/provider.dart';

class NewsView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return NewsViewState();
  }
}

class NewsViewState extends State<NewsView> with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  List<NewsCategory> categoryList = [];
  TabController controller;
  Future loadFuture;
  int tabIndex;

  @override
  void initState() {
    loadFuture = load().then((_) {
      controller = new TabController(
        length: categoryList.length,
        vsync: this,
      );

      controller.addListener(() {
        setState(() {
          tabIndex = controller.index;
        });
      });
    });

    super.initState();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return FutureBuilder(
      future: loadFuture,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          return body();
        }
        return Container();
      },
    );
  }

  Widget body() {
    return Scaffold(
      appBar: AppBar(
        title: Consumer<AppInfoModel>(
          builder: (cxt, vm, child) {
            return Text(vm.newsTitle);
          },
        ),
        centerTitle: true,
        leading: Consumer<AppInfoModel>(
          builder: (cxt, vm, child) {
            return Container(
              margin: EdgeInsets.fromLTRB(10, 10, 10, 10),
              child: vm.logoUrl.isEmpty
                  ? Image.asset(R.assetsCommonLogo)
                  : CachedNetworkImage(
                      imageUrl: vm.logoUrl,
                      fit: BoxFit.fitHeight,
                    ),
            );
          },
        ),
        bottom: tabbar(),
      ),
      body: tabView(),
    );
  }

  Widget tabbar() {
    return PreferredSize(
      preferredSize: Size(MediaQuery.of(context).size.width, 42),
      child: Container(
        alignment: Alignment.centerLeft,
        child: TabBar(
          isScrollable: true,
          tabs: createTabs(),
          controller: controller,
          labelPadding: EdgeInsets.all(10),
          unselectedLabelColor: Colors.black54,
          unselectedLabelStyle: TextStyle(fontWeight: FontWeight.normal, fontSize: 16),
          labelColor: Theme.of(context).primaryColor,
          labelStyle: TextStyle(fontWeight: FontWeight.normal, fontSize: 16),
          indicatorSize: TabBarIndicatorSize.label,
          indicatorColor: Theme.of(context).primaryColor,
        ),
      ),
    );
  }

  Widget tabView() {
    return TabBarView(
      children: categoryList.map((item) {
        return NewsListWidget(category: item);
      }).toList(),
      controller: controller,
    );
  }

  List<Widget> createTabs() {
    return categoryList.map((item) {
      return Text(item.name);
    }).toList();
  }

  @override
  bool get wantKeepAlive => true;

  Future load() async {
    var res = await Http.instance.post('/news-app/news/getnewscategors');
    if (res.code == 200) {
      categoryList = (res.data as List).map((item) {
        return NewsCategory.fromJson(item);
      }).toList();
    }
  }
}
